<style lang="scss" scoped>
@import "map";
</style>

<template>
  <div class="ws-qqmap" :style="{display:value?'block':'none'}" @click="isClose">
    <div class="ws-qqmap-main">
      <!-- 城市选择 start -->
      <div class="ws-qqmap-city" v-show="isShowCity">
        <div class="ws-city-header">
          <span class="title">{{ currentCity }}</span>
          <span class="close" @click="isShowCity=false">×</span>
        </div>
        <div class="ws-city-main" v-if="city.length">
          <el-row class="line30 p_y5" v-for="item of city">
            <el-col :span="4" class="a_c">
              {{ item.name }}
            </el-col>
            <el-col :span="20">
							<span v-for="v of item.children">
								<el-button @click="qqAddress(v)" class="m_r5" size="small"
                           :type="currentCity===v.name||currentCity.indexOf(v.name)>=0?'error':'default'">
									{{ v.name }}
								</el-button>
							</span>
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- 城市选择 end -->

      <div class="ws-qqmap-header">
				<span class="title">
					{{ currentCity }}
					<span class="title pointer" style="padding: 0px;el-color: #409EFF;" @click="showCity">【更换城市】</span>
				</span>
        <span class="close" @click="close(false)">×</span>
      </div>
      <el-row class="ws-qqmap-toolbar">
        <el-col :span="10">
          <el-input v-model="keyword" placeholder="检索关键字"></el-input>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-button type="primary" @click="search">搜索</el-button>
        </el-col>
        <el-col :span="2">
          <el-button @click="clearOverlays" v-show="isClear">清除检索标记</el-button>
        </el-col>
      </el-row>
      <el-row class="ws-qqmap-toolbar">
        <el-col :span="10">
          <el-input placeholder="坐标" :model-value="latLng.toString()" @input="(latLng)=>latLng=latLng"></el-input>
        </el-col>
        <el-col :span="13" :offset="1">
          <el-input placeholder="地址" v-model="address"></el-input>
        </el-col>
      </el-row>
      <!-- 腾讯地图区域 -->
      <div id="container"></div>
      <div class="ws-qqmap-footer m_t5">
        <el-button @click="close(false)" class="m_r10">取消</el-button>
        <el-button type="primary" @click="checkAddress">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import {qqMapUtil} from './qqMapUtil'
import {http} from '@/api/http'
import {Toast} from '@/utils/toast'
import {TMapServiceApi} from "@/components/qqMap/api/TMap";

export default {
  name: 'TMap',
  props: {
    // 是否显示组件
    value: {
      type: Boolean,
      default: false
    },
    // 是否显示组件
    qqMapKey: {
      type: String,
      default: '757BZ-WTU33-N2J3D-YCRJ3-N4KD6-HXFCD'
    },
    // 默认选中地址[lat,lng,address,keyword]
    defaultLatlng: Array,
    // 城市列表接口地址
    cityUrl: {
      type: String,
      default: '/map/cities'
      // required: true,
    },
    // 坐标转换地址接口地址
    locationUrl: {
      type: String,
      default: '/map/qqLocation'
      // required: true,
    }
  },
  data() {
    return {
      latLng: [], //选择的坐标
      address: '', // 详细地址
      keyword: '', //检索关键词
      isFirstSetDefaultCity: true,
      isShowCity: false, // 是否显示城市切换框
      city: [], //所有城市列表
      currentProvince: '北京市',
      currentCity: '北京市', // 当前城市
      map: null, // 腾讯地图（暂时不用）
      mapCenter: [], // 腾讯地图中心点（暂时不用）
      citylocation: null, // 腾讯地图 （城市筛选时使用）
      isClear: false // 是否显示清除标记按钮
    }
  },
  mounted() {
    this.changeDefaultLatlng(this.defaultLatlng)
  },
  watch: {
    // 用户初始定位变化监听
    defaultLatlng(val) {
      this.changeDefaultLatlng(val)
      this.empty(val)
    },
    // 用户地址选择变化监听
    latLng(newVal) {
      if (!newVal.lat || !newVal.lng) {
        return
      }
      http(TMapServiceApi.location2Address, {
        location: `${newVal.lat},${newVal.lng}`,
        key: this.qqMapKey
      }).then(({status, result, message}) => {
        if (status === 0) {
          if (result.address_component) {
            let city = result.address_component.city
            this.currentCity = result.address_component.city
            qqMapUtil.setLocation(city)
          }
          this.address = result.address
        } else if (message) {
          Toast(message, 'warning')
        }

      })

    }
  },
  methods: {
    // 用户改变了初始定位
    changeDefaultLatlng(latLng, isInit = true) {
      let rs = {}
      if (latLng && latLng[0] && latLng[1]) {
        this.isFirstSetDefaultCity = false
        rs = {latLng, has: true}
      } else {
        rs = {latLng: [39.916527, 116.397128], has: false}
      }
      if (isInit) {
        this.map = qqMapUtil.init(this, rs.latLng, rs.has, this.qqMapKey)
      } else if (this.isFirstSetDefaultCity) {
        this.isFirstSetDefaultCity = false
        var center = new qq.maps.LatLng(latLng[0], latLng[1])
        this.citylocation.searchCityByLatLng(center)
      }
    },
    // 初始化
    empty(val) {
      val = Array.isArray(val) ? val : []
      if (val.length > 1) {
        this.latLng = [val[0], val[1]]
      } else {
        this.latLng = []
      }
      if (val.length > 2) {
        this.address = val[2]
      } else {
        this.address = ''
      }
      if (val.length > 3) {
        this.keyword = val[3]
      } else {
        this.keyword = ''
      }
    },
    // 关闭地图选择框
    close(val = false) {
      this.$emit('input', val)
      this.$emit('update:value', val)
    },
    // 是否点击模态框（关闭地图框）
    isClose(e) {
      if (e.target.className === 'ws-qqmap') {
        this.close()
      }
    },
    // 腾讯地图搜索按钮点击触发
    search() {
      if (this.keyword.length) {
        qqMapUtil.searchKeyword(this.keyword)
        this.isClear = true
      }

    },
    // 确定选择 地址
    checkAddress() {
      if (!this.address.length) {
        Toast('请先点击地图选择地址', 'warning')
        return
      }
      this.close()
      this.$emit('check', {
        address: this.address,
        latLng: this.latLng,
        city: this.currentCity,
        province: this.currentProvince
      })
    },
    // 点击打开城市更换框
    showCity() {
      if (!this.city.length) {
        http({
          path: this.cityUrl
        }).then(res => {
          this.city = res.data
        })
      }
      this.isShowCity = !this.isShowCity
    },
    // 选择城市后触发（地址转坐标）
    qqAddress(city) {

      this.currentProvince = city.name
      if (this.citylocation) {
        this.citylocation.searchCityByName(city.name)
        this.isShowCity = false
        this.empty()
      }
    },
    // 清除检索标记
    clearOverlays() {
      qqMapUtil.clearOverlays()
      this.isClear = false
    }
  }
}
</script>
